using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;
using aprogblog.Domain.Helpers;

namespace aprogblog.Domain.Classes {

    public class BlogClass : Blog {
    
        SyndicationFeed feed;
        public virtual SyndicationFeed Feed { get { return feed ?? InitFeed; }}
        SyndicationFeed InitFeed { get { return feed = Load(); } }
        
        public Entry FindById(string Id) { return
            Feed.Items.Where(Item => Item.Id == Id)
                .Single().ToEntry()
        ;}

        public List<Entry> RecentEntries(int NumberOfEntries) { return
            Feed.Items.Reverse().Take(NumberOfEntries).ToEntries()
        ;}

        public void Add(Entry Entry) { 
            Feed.Items = Feed.Items.Concat(new[] { Entry.ToItem() });
            Save();
        }

        public void Delete(string Id) {
            Feed.Items = Feed.Items.Where(Item => Item.Id != Id);
            Save();
        }

        #region persist
        
        public string FeedPath { get; set; }

        public virtual SyndicationFeed Load() {
            using (var RSSReader = XmlReader.Create(FeedPath))
                return SyndicationFeed.Load(RSSReader);
        }

        public virtual void Save() {
            using (var RSSWriter = XmlWriter.Create(FeedPath))
                FeedFormatter.WriteTo(RSSWriter);
        }

        Rss20FeedFormatter FeedFormatter { get { return
            new Rss20FeedFormatter(Feed)
        ;}}

        #endregion
    }
}